package cn.chiship.framework.docs.core.properties;

import cn.chiship.framework.common.constants.CommonConstants;
import cn.chiship.framework.common.constants.SystemConfigConstants;
import cn.chiship.framework.common.pojo.vo.ConfigJson;
import cn.chiship.framework.common.service.GlobalCacheService;
import cn.chiship.sdk.cache.service.RedisService;
import cn.chiship.sdk.core.base.constants.BaseCacheConstants;
import cn.chiship.sdk.core.util.FileUtil;
import cn.chiship.sdk.core.util.PlatformUtil;
import cn.chiship.sdk.core.util.StringUtil;
import cn.chiship.framework.common.constants.CommonCacheConstants;
import cn.chiship.framework.docs.biz.entity.FileCatalogConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author lijian
 */
@Configuration
@Component
public class FileUploadProperties {

	private static final String SLASH = "/";

	@Value("${file.remote.host}")
	private String remoteHost;

	@Value("${file.remote.port}")
	private String remotePort;

	@Value("${file.remote.dir.windows}")
	private String remoteWindowsDir;

	@Value("${file.remote.dir.linux}")
	private String remoteLinuxDir;

	@Autowired
	RedisService redisService;

	@Resource
	GlobalCacheService globalCacheService;

	public Byte getStorageLocation() {
		ConfigJson configJson = globalCacheService.getSystemConfigJson(SystemConfigConstants.STORAGE_LOCATION);
		if (!StringUtil.isNull(configJson)) {
			return Byte.valueOf(configJson.getString(SystemConfigConstants.STORAGE_LOCATION));
		}
		else {
			return 0;
		}
	}

	/**
	 * 获取http访问前缀
	 * @return
	 * @throws NullPointerException
	 */
	public String getHttpFilePrefix() throws NullPointerException {
		StringBuilder builder = new StringBuilder("http://");
		builder.append(remoteHost);
		builder.append(":");
		builder.append(remotePort);
		builder.append("/");
		return builder.toString();
	}

	/**
	 * 获取相对路径（含COMMON_PROJECT_NAME）
	 * @return
	 * @Example CHISHIP_FRAMEWORK
	 */
	public String getFileUrl() {
		return getFileUrl(null);
	}

	/**
	 * 获取相对路径（含COMMON_PROJECT_NAME）
	 * @param filePath
	 * @return
	 * @Example CHISHIP_FRAMEWORK
	 */
	public String getFileUrl(String filePath) {
		StringBuilder builder = new StringBuilder();
		builder.append(CommonConstants.COMMON_PROJECT_NAME);
		if (!StringUtil.isNullOrEmpty(filePath)) {
			builder.append("/");
			builder.append(formatFilePath(filePath));
		}
		return builder.toString();
	}

	/**
	 * 获取绝对对路径（含COMMON_PROJECT_NAME）
	 * @return
	 * @Example c:\FileServer\CHISHIP_FRAMEWORK
	 */
	public String getFileAbsolutePath() {
		return getFileAbsolutePath(null);
	}

	/**
	 * 获取绝对对路径（含COMMON_PROJECT_NAME）
	 * @param filePath
	 * @return
	 * @Example c:\FileServer\CHISHIP_FRAMEWORK or /usr/local/FileServer/CHISHIP_FRAMEWORK
	 */
	public String getFileAbsolutePath(String filePath) {
		StringBuilder builder = new StringBuilder();
		builder.append(getRemoteDir());
		builder.append("/");
		builder.append(CommonConstants.COMMON_PROJECT_NAME);
		if (!StringUtil.isNullOrEmpty(filePath)) {
			builder.append("/");
			builder.append(formatFilePath(filePath));
		}
		try {
			FileUtil.forceMkdir(new File(builder.toString()));
		}
		catch (Exception e) {

		}
		return builder.toString();
	}

	/**
	 * 获得文件相对路径根据文件夹ID
	 * @param catalogId
	 * @return
	 */
	public String getFilePathByCatalogId(String catalogId) {
		String path = "";
		FileCatalogConfig fileCatalogConfig = (FileCatalogConfig) redisService
				.hget(CommonCacheConstants.buildKey(BaseCacheConstants.REDIS_FILE_CATALOG_CONFIG_PREFIX), catalogId);
		if (fileCatalogConfig != null) {
			path = fileCatalogConfig.getCatalogPath();
			path = getFilePathByCatalogId(fileCatalogConfig.getCatalogPid()) + "/" + path;
		}
		return path;
	}

	/**
	 * 根据上传的文件路基获得完整路径
	 * @param filePath
	 * @return
	 */
	public String getUploadFullPath(String filePath) {
		return getRemoteDir() + "/" + filePath;
	}

	public Boolean removeFile(String filePath) {
		filePath = getUploadFullPath(filePath);
		File file = new File(filePath);
		if (!file.exists()) {
			return false;
		}
		return file.delete();
	}

	private String formatFilePath(String filePath) {
		if (filePath.indexOf(SLASH) == 0 && filePath.lastIndexOf(SLASH) == filePath.length() - 1) {
			return filePath.substring(1, filePath.length() - 1);
		}
		else if (filePath.lastIndexOf(SLASH) == filePath.length() - 1) {
			return filePath.substring(0, filePath.length() - 1);
		}
		else if (filePath.indexOf(SLASH) == 0) {
			return filePath.substring(1);
		}
		else {
			return filePath;
		}
	}

	public String getRemoteHost() {
		return remoteHost;
	}

	public void setRemoteHost(String remoteHost) {
		this.remoteHost = remoteHost;
	}

	public String getRemotePort() {
		return remotePort;
	}

	public void setRemotePort(String remotePort) {
		this.remotePort = remotePort;
	}

	public String getRemoteWindowsDir() {
		return remoteWindowsDir;
	}

	public void setRemoteWindowsDir(String remoteWindowsDir) {
		this.remoteWindowsDir = remoteWindowsDir;
	}

	public String getRemoteLinuxDir() {
		return remoteLinuxDir;
	}

	public void setRemoteLinuxDir(String remoteLinuxDir) {
		this.remoteLinuxDir = remoteLinuxDir;
	}

	public String getRemoteDir() {
		if (PlatformUtil.isLinux()) {
			return remoteLinuxDir;
		}
		return remoteWindowsDir;
	}

}
